const app = getApp();
const AJAX = app.$ajax,
  $wx = app.$wx;

Page({
  data: {
    imgHost: app.imgHost,
    textareaVal: '',
    uploadImgs: []
  },

  onLoad(options){
    this.setData({
      commodityIndex: options.commodity_index
    });
    this.getOrderList();
  },

  onShareAppMessage(){

  },

  inputTextarea(e){
    let val = e.detail.value;

    this.setData({
      textareaVal: val
    });
  },

  selectedUploadImg(){
    let _this = this, td = _this.data;

    $wx.uploadSourceType([], res => {
      let img = res.tempFilePaths[0];
      td.uploadImgs.push(img);
      _this.setData({
        uploadImgs: td.uploadImgs
      });
    });
  },

  removeImg(e){
    let td = this.data, 
        ed = e.currentTarget.dataset;
    
    td.uploadImgs.splice(ed.index, 1);
    this.setData({
      uploadImgs: td.uploadImgs
    });
  },

  upload(){
    let td = this.data, 
        order_detail_item = td.orderDetail.goods[0];
      
    if (td.textareaVal.length === 0){
      $wx.showToast('请输入您的评价');
    }else{
      let upload_res = [];
      $wx.uploadFile({
        url: AJAX.uploadFile,
        filePath: td.uploadImgs,
        name: 'file',
        success(res){
          upload_res.push(JSON.parse(res.data).data.url);
        },
        complete(res) {
          AJAX.comment({
            loadType: 'default',
            loadMsg: '评价中...',
            goods_id: order_detail_item.goods_id,
            order_id: order_detail_item.order_id,
            content: td.textareaVal,
            images: JSON.stringify(upload_res)
          }).then(([status, res, msg]) => {
            $wx.showToast(msg, {
              success(){
                if(status){
                  setTimeout(callback => {
                    wx.navigateBack();
                  }, 2000);
                }
              }
            });
          });
        }
      })
    
    }
  },

  getOrderList() {
    let td = this.data;
    AJAX.orderList({
      loadType: 'bar',
      status: 4
    }).then(([status, res, msg]) => {
      if (status) {
        this.setData({
          orderDetail: res[td.commodityIndex]
        });
      } else {
        $wx.showToast(msg);
      }
    });
  } 
})